package com.bdqn.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
public class OSSUtil {
    public static final String ALI_DOMAIN =  "https://phone-manage1.oss-cn-beijing.aliyuncs.com";
    public static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    public static final String accessKeyId = "LTAI5tSZfPKcfjPMRCEC288m";
    public static final String accessKeySecret = "gS1YI3lKkfYdlLWLknF3ABBqNre7ul";

    public static String uploadImage(MultipartFile file) throws IOException {
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String ext = "."+ FilenameUtils.getExtension(originalFilename); // 后缀
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String fileName = uuid+ext;
        // 地域节点
        // OSS 客户端对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(
               "phone-manage1",
                fileName,
                file.getInputStream()
        );
        ossClient.shutdown();
        return ALI_DOMAIN+"/"+fileName;
    }
    public static void delete(String url){
            url = url.substring(url.indexOf("//") + 2);
            url = url.substring(url.indexOf("/") + 1);
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject("phone-manage1",url);
            ossClient.shutdown();
    }
}
